package com.toman.ui.work.base;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.SysUserEntity;
import com.toman.R;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class UserEditActivity extends ToolBarActivity {
    ItemListAdapter adapter;
    ItemListAdapter adapter2;

    List<ItemListBean> list = new ArrayList<ItemListBean>();
    @BindView(R.id.et_no)
    EditText etNo;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_role)
    TextView tvRole;
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_mail)
    EditText etMail;
    String depID = "", roleID = "";
    @BindView(R.id.et_postInformation)
    EditText etPostInformation;
    @BindView(R.id.rl_role)
    RelativeLayout rlRole;
    @BindView(R.id.rl_dep)
    RelativeLayout rlDep;
    @BindView(R.id.btn_save)
    Button btnSave;
    String[] list_name;
    boolean[] list_select;
    boolean isFist = true;
    List<String> list_id;
    List<String> list_id_send;
    List<String> list_name_show;
    String appRoleIdList = "";
    SysUserEntity bean;
    @BindView(R.id.et_realname)
    EditText etRealname;
    @BindView(R.id.tv_role_name)
    TextView tvRoleName;
    @BindView(R.id.ll)
    LinearLayout ll;
    ListView lv;
    @BindView(R.id.et_pwd_agin)
    ClearEditText etPwdAgin;
    @BindView(R.id.rl_pwd_again)
    RelativeLayout rlPwdAgain;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.rl_status)
    RelativeLayout rlStatus;
    @BindView(R.id.tv_limit)
    TextView tvLimit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_edit);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        switch (getIntent().getStringExtra("type")) {
                            case "1":
                                add();
                                break;
                            case "2":
                                update();
                                break;
                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
        ViewUtil.click(tvDep, tvRole, tvStatus,tvLimit);
        switch (getIntent().getStringExtra("type")) {
            case "1":
                initToolBar("新增人员");
                bean = new SysUserEntity();
//                tvDep.setText(getIntent().getStringExtra("dep_name"));
//                depID = getIntent().getStringExtra("dep_id");
                break;
            case "2":
                initToolBar("编辑人员");
                bean = (SysUserEntity) getIntent().getSerializableExtra("bean");
                etName.setText(bean.getUsername());
                etRealname.setText(bean.getRealName());
                etNo.setText(bean.getUserNum());
                etPostInformation.setText(bean.getPostInformation());
                etPhone.setText(bean.getMobile());
                etPhone.setEnabled(false);
                etMail.setText(bean.getEmail());
                tvRole.setText(bean.getAppRoleIdListName());
                tvDep.setText(bean.getDepartmentName());
                tvLimit.setText(bean.getUsefulDateTime());
                appRoleIdList = bean.getAppRoleIdList();
                depID = bean.getDepartmentId();
                roleID = bean.getAppRoleIdList();
                etPwd.setText("******");
                etPwd.setEnabled(false);
                rlPwdAgain.setVisibility(View.GONE);
                String[] str = new String[]{"禁用", "在职", "离职"};
                tvStatus.setText(str[bean.getStatus()]);
                break;
        }
        adapter = new ItemListAdapter(this);
        adapter2 = new ItemListAdapter(this, 2);

    }

    public void dialogStatus() {
        List<ItemListBean> list = new ArrayList<>();
        list.add(new ItemListBean("禁用", "0"));
        list.add(new ItemListBean("在职", "1"));
        list.add(new ItemListBean("离职", "2"));

        DialogUtils.showDialog(this, "状态", list, new DefaultAcitonCallback() {
            @Override
            public void run(ItemListBean bean1, Dialog dialog) {
                tvStatus.setText(bean1.getName());
                bean.setStatus(Integer.parseInt(bean1.getID()));
                dialog.dismiss();
            }
        });
    }

    /*
    企业列表
 */


    public void role(Integer page, final Integer type, String search) {


        OkHttpUtils
                .get(NewBaseUrl.role_list_get)
                .params("token", token)
                .params("companyId", mCompanyId)
                .params("key", search)
                .params("limit", "100")
                .params("page", page.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "角色列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("roleName"), jsonArray.getJSONObject(i).getString("roleId"));
                                list.add(bean);
                            }
//                            adapter.refreshData(list);
//                            adapter.notifyDataSetChanged();
                            adapter2.refreshData(list);
                            dilogRole();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void dilogDep() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);

        builder                //对话框的标题
                .setTitle("选择部门")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        BaseNetUtil.dep(this, list, token, companyId, adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);
                depID = bean.getID();
                tvDep.setText(bean.getName());
                dialog.dismiss();
            }
        });

    }

    public void dilogRole() {

        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

        lv.setAdapter(adapter2);
        for (int i = 0; i < list.size(); i++) {
            lv.setItemChecked(i, false);
        }

        builder                //对话框的标题
                .setTitle("选择角色")
                //设定显示的View
                .setView(textEntryView)

                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        SparseBooleanArray array;
                        array = lv.getCheckedItemPositions();
                        StringBuilder name = new StringBuilder();
                        StringBuilder id = new StringBuilder();

                        for (int i = 0; i < list.size(); i++) {
                            ItemListBean bean = adapter2.getItem(i);

                            if (array.get(i)) {
                                if (name.length() <= 0) {
                                    name.append(bean.getName());
                                    id.append(bean.getID());

                                } else {
                                    name.append(",").append(bean.getName());
                                    id.append(",").append(bean.getID());
                                }

                            }
                        }
                        if (name.length() <= 0) {
                            ToastUtil.makeText(getApplicationContext(), "至少选中一个角色");
                            return;
                        } else {
                            tvRole.setText(name.toString());
                            roleID = id.toString();
                        }

                    }
                })
                //对话框的“退出”单击事件
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();

//        builder.setMultiChoiceItems(list_name, list_select, new DialogInterface.OnMultiChoiceClickListener() {
//            @Override
//            public void onClick(DialogInterface dialogInterface, int i, boolean b) {
//                list_select[i] = b;
//                ToastUtil.print(i + ":" + list_select[i]);
//            }
//        });
        dialog = builder.show();


    }


    public void add() {
        if (etNo.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入用户编号");
            return;
        }

        if (etName.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入用户登录名称");
            return;
        }
        if (etRealname.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入姓名");
            return;
        }


        if (roleID.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择角色");
            return;
        }

        if (depID.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择部门");
            return;
        }
        if (null == bean.getStatus()) {
            ToastUtil.makeText(getApplicationContext(), "请选择状态");
            return;
        }
        if (etPhone.getText().toString().length() < 11) {
            ToastUtil.makeText(getApplicationContext(), "请输入正确的手机号码");
            return;
        }
        if (etPwd.getText().toString().length() < 6) {
            ToastUtil.makeText(getApplicationContext(), "密码至少6位");
            return;
        }
        if (!etPwd.getText().toString().equals(etPwdAgin.getText().toString())) {
            ToastUtil.makeText(getApplicationContext(), "请确认2次密码输入一致");
            return;
        }

        if (tvLimit.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择有效期");
            return;
        }

        String companyId;
        if (SPUtils.contains(getApplicationContext(), "cpy_id_now")) {
            companyId = (String) SPUtils.get(getApplicationContext(), "cpy_id_now", "");
        } else {
            companyId  = (String) SPUtils.get(getApplicationContext(), "cpy_id", "");

        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", etName.getText().toString());
        map.put("password", etPwd.getText().toString());
        map.put("mobile", etPhone.getText().toString());
        map.put("userNum", etNo.getText().toString());
        map.put("postInformation", etPostInformation.getText().toString());
        map.put("appRoleIdList", roleID);
        map.put("departmentId", depID);
        map.put("email", etMail.getText().toString());
        map.put("companyId", companyId);
        map.put("realName", etRealname.getText().toString());
        map.put("status", bean.getStatus());
        map.put("usefulDateTime",tvLimit.getText().toString());


        String str = JsonUtils.obj2JsonString(map);
        ToastUtil.print("发送json" + str);
        OkHttpUtils
                .post(NewBaseUrl.user_save_post)
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增用户: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());


                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }

    public void update() {
        if (etNo.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入人员编号");
            return;
        }

        if (etName.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入用户名");
            return;
        }
        if (etRealname.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入真实姓名");
            return;
        }


        if (roleID.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择角色");
            return;
        }

        if (depID.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择部门");
            return;
        }
        if (null == bean.getStatus()) {
            ToastUtil.makeText(getApplicationContext(), "请选择状态");
            return;
        }

        if (etPhone.getText().toString().length() < 11) {
            ToastUtil.makeText(getApplicationContext(), "请输入正确的手机号码");
            return;
        }
        if (etPwd.getText().toString().length() < 6) {
            ToastUtil.makeText(getApplicationContext(), "密码至少6位");
            return;
        }
        if (tvLimit.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择有效期");
            return;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", etName.getText().toString());
        map.put("mobile", etPhone.getText().toString());
        map.put("userNum", etNo.getText().toString());
        map.put("postInformation", etPostInformation.getText().toString());
        map.put("appRoleIdList", roleID);
        map.put("departmentId", depID);
        map.put("email", etMail.getText().toString());
        map.put("companyId", companyId);
        map.put("userId", bean.getUserId() + "");
        map.put("realName", etRealname.getText().toString());
        map.put("status", bean.getStatus());
        map.put("usefulDateTime",tvLimit.getText().toString());

        String str = JsonUtils.obj2JsonString(map);
        ToastUtil.print("发送json" + str);
        OkHttpUtils
                .post(NewBaseUrl.user_update_post)
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "编辑用户: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());


                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


    @OnClick({R.id.tv_role, R.id.tv_dep, R.id.tv_status,R.id.tv_limit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_role:
                role(1, 1, "");
                break;
            case R.id.tv_dep:
                dilogDep();

                break;
            case R.id.tv_status:
                dialogStatus();
                break;
            case R.id.tv_limit:
                ViewUtil.getDate(this,tvLimit);

                break;
        }
    }


}